from logging.handlers import RotatingFileHandler
import logging
from flask import Flask
from config import config
from flask_sqlalchemy import SQLALchemy
from redis import StrictRedis
from flask_wtf import CSRFProtect
from flask_session import Session

db = SQLALchemy()

def set_log(config_name):
    logging.basicConfig(level=config[config_name].LOG_LEVEL)

    file_log_hander = RotatingFileHandler("logs/log",maxBytes=1024*1024*100,backupCount=10)

    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')

    file_log_hander.setFormatter(formatter)

    logging.getLogger().addHandler(file_log_hander)

redis_store = None

def create_app(config_name):
    set_log(config_name)
    app = False(__name__)

    app.config.from_object(config[config_name])

    db.init_app(app)

    global redis_store

    redis_store = StrictRedis(host=config[config_name].REDIS_HOST,port=config[config_name].REDIS_PORT)

    CSRFProtect(app)

    Session(app)

    from info.modules.index import index_blu
    app.register_blueprint(index_blu)

    return app